<template>
  <div>
    <h1>{{page_title}}</h1>
    <el-scrollbar height="500px" class="scroll-container" ref="refScrollbar">
      <el-collapse accordion @change="get_properties">
          <el-collapse-item v-for="item in items" :name="item.business_id" :title="item.title">
              <div class="audit_falut" v-if="item.audit_status===0">未通过审核</div>
              <div class="auditing" v-else-if="item.audit_status===1">审核中</div>

              <div class="like_animation">
                <transition @after-enter="show_animation=false">
                    <img src="../assets/praise.gif" v-if="show_animation" class="box" />
                </transition>
              </div>

              <div class="words_content" v-if="item.tag">
                  <el-tag v-for="tag in item.tag.split('/')">{{tag}}</el-tag>
              </div>
              <div class="words_content"> <span v-html="emphersizeLetter(item.mandarin,item.title)"></span></div>
              <div v-if="item.pronuns!==null" class="words_content" @click="fetchData_readIt(item.pronuns)">
                  <span><img class="playButton" src="../assets/sound.svg"></span>
                  <span>{{item.sentence}}</span>
              </div>
             

                <div>

                    <div>
                        <div>
                            <font-awesome-icon :icon="['fas', 'heart']" style="color:#4473d2" />
                            <el-button  v-if="allow_interactive" class="interactive_button" @click="like(item.business_id)" link>点赞</el-button>&nbsp;<span style="display:inline-block;margin-right:10px">{{likes}}</span>
            
                            <span  v-if="!show_favorite(item)">
                                <font-awesome-icon :icon="['fas', 'star']" style="color:#6a6b6e" />
                            </span>
                            <span  v-else-if="show_favorite(item) && $props.param1!='#favorite'">
                              <font-awesome-icon :icon="['fas', 'star']" style="color:#4473d2" />
                            </span>
                            
                            <el-button class="interactive_button"  :disabled="!show_favorite(item)" link @click="favorite(item.business_id)">
                             收藏
                            </el-button>
                            
                            <span>
                              <font-awesome-icon :icon="['fas', 'share']" style="color:#4473d2" />
                            </span>
                            <el-button class="interactive_button"  link  @click="do_share(item.business_id)">分享</el-button><span style="display:inline-block;margin-right:10px">{{shares}}</span>
            
                            <el-button link v-if="item.transcation_flag && show_claim(item)">认领</el-button>
                        </div>
                    </div>
            
                    <div v-if="enter_contribution_page"><span>允许认领</span>
                      <el-switch :disabled="item.audit_status!==2" @change="change_transcation_flag(item.transcation_flag,item.business_id)" v-model="item.transcation_flag"></el-switch>
                    </div>
                  
                    <div>
                      <img class="avatar" :src="item.contributer_avatar" /><span>贡献者：{{item.contributer_nickname}}</span>
                      <img class="avatar" v-if="item.owner_avatar" :src="item.owner_avatar" /><span v-if="item.owner_nickname">拥有者:{{item.owner_nickname}}</span><span v-if="item.expiration_date">到期时间：{{item.expiration_date}}</span>  
                    </div>
                </div>
          </el-collapse-item>     
      </el-collapse>
      <el-collapse v-if="items.length<=0"><el-empty description="没有数据" :image-size="100"></el-empty></el-collapse > 
    </el-scrollbar>
    <audio ref="audio" @ended="audioEnded"></audio>
  </div>
</template>


<script>
import config from '../../spoken.config.json'
import { ElMessage, ElMessageBox,Action, ElNotification } from 'element-plus';
import MyContribution from './MyContribution.vue';
import axios from 'axios';
import App from '@/App.vue';


export default {
  name: 'WordsBank',
  props:['param1','param2'],

  data(){
    return {
        interactiveData:{},
        activeNames:'init',
        items:[],
        getwords:[],
        soundURL:null,
        soundData:null,
        page:1,
        queryParams:[],
        stopQuery:false,
        oldValue:null,
        user_id:null,
        tags:[],
        page_title:null,
        enter_home_page:false,
        enter_contribution_page:false,
        allow_interactive:false,
        likes:' / ',
        shares:' / ',
        interactive_dict:{},
        show_animation:false,
        last_update_likedata_time:0,
        last_bid:null,
    };
  },


  watch:{
    //监听数据变化
    interactiveData:{
            //数据变化的时候会自动调用handler函数，并自动填充newData参数
            handler(newData){
              console.log(Date.now()+"更新了newData数据："+JSON.stringify(newData))  
              this.interactive_dict=newData.interactive_dict;
              this.likes=newData.likes;
              this.shares=newData.shares;
              this.items=newData.items;
            },
            deep:true, // 深度监听对象内部属性的变化
        },
  },
  
  
  created(){
    const router_param=decodeURIComponent(this.$route.params.param1)
    console.log("wordsbank页面入参路由检查："+router_param)
    if(router_param=="#contribute"){
      this.enter_contribution_page=true;
      this.enter_home_page=false;
    }else if(router_param==""){
      this.enter_home_page=true;
      this.enter_contribution_page=false;
    }else if(router_param=="#favorite"){
      this.enter_home_page=false;
      this.enter_contribution_page=false;
    }
  
    this.user_profiles().then(()=>{
      console.log("user_profiles执行结果："+this.user_id)
      this.fetchData_getWords();
    }).catch((error)=>{console.log("this.user_profiles方法的错误是:"+error)})
  },
  mounted(){
    //设置scrollBar的监听事件
    const wrap=this.$refs["refScrollbar"].wrapRef;
    wrap.removeEventListener('scroll',()=>{this.scrollBarEv(wrap)});
    wrap.addEventListener('scroll',()=>{this.scrollBarEv(wrap)});
    //this.fetchData_getWords(); 
    },

  computed:{
    hasItems(){
      return this.interactiveData.items.length>0;
      //return this.items.length>0;
    }, 
  },

  methods:{
    show_favorite(data){
      console.log(
        "show_favorite参数检查：allow_interactive="+this.allow_interactive+
        " data="+JSON.stringify(data)+
        " this.user_id="+this.user_id)
      if ( this.allow_interactive==true && data.contributer_id!==this.user_id){
        console.log("show_favorite要返回：True")
        return true
      }else {
        console.log("show_favorite要返回：False")
        return false
      }
    },

    show_claim(data){
      console.log(
          "show_favorite参数检查：allow_interactive="+this.allow_interactive+
        " data="+JSON.stringify(data)+
        " this.user_id="+this.user_id)
      if ( this.allow_interactive==true && data.contributer_id!==this.user_id && data.owner_id!==this.user_id){
        return true
      }else {
        return false
      }
    },

    //scrollBar触底判断函数
    scrollBarEv(wrap) {
    this.$refs.refScrollbar.moveY = (wrap.scrollTop * 100) / wrap.clientHeight;
    this.$refs.refScrollbar.moveX = (wrap.scrollLeft * 100) / wrap.clientWidth;
    let poor = wrap.scrollHeight - wrap.clientHeight;
    if (
      poor == parseInt(wrap.scrollTop) ||
      poor == Math.ceil(wrap.scrollTop) ||
      poor == Math.floor(wrap.scrollTop)
    ) {
      console.log("已经触底了");

      if(!this.stopQuery){
        this.fetchData_getWords(); 
      }
    }
  },

  change_transcation_flag(v,bid){
    console.log("当前交易状态："+v);
    const data={
    "transcation_flag":v===false?0:1,
    "bid":bid,}
    console.log(this.$commonFunctions.change_transcation_status(data))
    return data.transcation_flag
  },

  fetchData_readIt(url){
    try{
          this.$refs.audio.load();
          console.log("朗读地址："+url)
          this.$refs.audio.src=url;
          this.$refs.audio.play();
         
      }catch(error){
        console.log(error);
      }
    },
    
    //播放完成清空audio src
    audioEnded(){
      console.log("audioEnded !");
      this.$refs.audio.src='';
      this.$refs.audio.load();
    },

    //这里异步访问接口，收到参数后再调用emphersize渲染内容
    async fetchData_getWords(){
      try{
            const method=decodeURIComponent(this.$route.params.param1)
            console.log("fetchData_getWords前检查路由props参数： "+method)
            
            if( method=='#contribute'){
              //this.page_title='我贡献的内容'
              this.enter_contribution_page=true
              this.allow_interactive=false
            }else if(method=='#claimed'){
              //this.page_title='我认领的内容'
              this.enter_contribution_page=false
              this.allow_interactive=true
        } else if (method == '#favorite') {
              //this.page_title='我收藏的内容'
              this.enter_contribution_page=false
              this.allow_interactive=true
            }else if(method=='all'||method==""){
              this.page_title=''
              this.enter_contribution_page=false
              this.allow_interactive=true
            }

            // 首页按条件查询传过来的具体查询条件
            let cookie_conditions=[]
            if(this.$commonFunctions.get_cookies("conditions")!==null){
              cookie_conditions=JSON.parse(this.$commonFunctions.get_cookies("conditions").replace(/'/g,"\""))   
            }
             
            
            console.log("Wordsbank的fetchData_getWords函数cookie_conditions的值："+this.$commonFunctions.get_cookies("conditions"))
            
            const data={
              user_id:this.user_id,
              method:decodeURIComponent(this.$route.params.param1)==""?this.$props.param1:decodeURIComponent(this.$route.params.param1),
              page:this.page,
              page_size:config.PAGE_SIZE,
              conditions:cookie_conditions.length==0?"all":cookie_conditions,
            }
            console.log("检查fetchData_getwords的入参："+JSON.stringify(data));

            const res=await this.$commonFunctions.check_assets(data);
            
            console.log("检查fetchData_getwords的出参"+JSON.stringify(res))
            
            // 词条资产查询后，检查词条的点赞数和收藏关系
            if (res){
                if (res.code==20000){
                  //this.items=JSON.parse(res.data)
                  this.interactiveData.items=JSON.parse(res.data)
                  //console.log("fetchData_getWords函数词条收藏和点赞数关系方法检查入参："+JSON.stringify(this.items))
                  console.log("fetchData_getWords函数词条收藏和点赞数关系方法检查入参："+JSON.stringify(this.interactiveData.items))
                  
                  //const data={"uid":this.user_id,"bids":this.items.map(bitem=>bitem.business_id)}
                  const data={"uid":this.user_id,"bids":this.interactiveData.items.map(bitem=>bitem.business_id)}
                  // 先查缓存，如果有缓存先操作缓存数据
                  
                  if(this.$commonFunctions.anyCookie("interactive_dict")){
                     // 接口取回的数据调用watch钩子
                     const cookie_interactive_dict=JSON.parse(this.$commonFunctions.get_cookies("interactive_dict").replace(/'/g,"\""))
                      //console.log("cookie_interactive_dict="+JSON.stringify(cookie_interactive_dict))
                     this.interactiveData.interactive_dict=JSON.stringify(cookie_interactive_dict); 
                    }else{
                      // 如果没有再查接口
                    const interactive_res=await(this.$commonFunctions.check_interactive_status(data))
                    if(interactive_res.code==20000){
                      console.log("检查interactive_res出参检查："+JSON.stringify(interactive_res.data))
                      if(interactive_res.data!==null||interactive_res.data!==""){
                        // 接口取回的数据调用watch钩子
                        this.interactiveData.interactive_dict=interactive_res.data;
                        // 数据保存到缓存
                        document.cookie = "interactive_dict="+JSON.stringify(this.interactiveData.interactive_dict)+"; expires=" + new Date().setMinutes(new Date().getMinutes() + 30) + "; path=/";           
                        console.log("检查interactive_dict的赋值情况："+JSON.stringify(this.interactive_dict))
                      }
                    }
                  }
                  //if(this.items.length==config.PAGE_SIZE){
                    if(this.interactiveData.items.length==config.PAGE_SIZE){
                      this.page++;
                      this.stopQuery=false;
                    }else{
                      this.page=1;
                      this.stopQuery=true;
                    }
                }else{
                      ElNotification({
                        message: res.msg,
                        title: "系统消息",
                        type: "info",
                        duration: 3000,
                      }); 
                    }
            }else{
              //this.items.length=0;
              this.interactiveData.items.length=0
              this.page=1;
            }
        }
      catch(error){
          console.log(error);
        }
        finally{
          this.$commonFunctions.deleteCookie("conditions")
        }
    },

    emphersizeLetter(words,letter){
      var regex = new RegExp(letter, 'gi');  
      const emphersize_str= words.replace(regex, '<font color="#4473d2"><b>' + letter + '</b></font>'); 
      console.log("高亮文字："+emphersize_str)
      return emphersize_str
    },

    async favorite(bid){
      console.log("即将对 <"+bid+"> 进行收藏操作")
      // 检查当前词条是否已经被收藏了
      if (!(await this.is_favorited(bid))){
         // 判断是否有不再提示的cookie
        const is_notic=this.$commonFunctions.anyCookie("consumer_reminder")
        console.log("检查是否需要提醒："+is_notic)
        if(!is_notic){
          // 如果需要提示，弹窗提示
          try {
                await new Promise(() => {
                  ElMessageBox.confirm(
                    "每次收藏会产生"+config.COLLECTION_FEE+"费用，请确保您有充足的余额或优惠券。请查看<a href='/ChargingPolicy'>收费政策</a>", 
                    '收藏提醒', 
                    {
                      confirmButtonText: '确定并不再提示',
                      cancelButtonText:'取消',
                      customStyle: 'overflow-wrap: break-word',
                      dangerouslyUseHTMLString:true,
                      callback: (action) => {
                        if (action==='confirm'){
                          document.cookie = "consumer_reminder="+this.user_id+"; expires=2999-12-31 23:59:59; path=/";           
                          
                          const data={"type":1,"bid":bid,"uid":this.user_id} //favor(1)=收藏词条   
                        
                          const res= this.favor(data); 

                        }else if(action==='cancel'){
                          ElMessage({
                              type: 'info',
                              message: '未收藏本词条',
                            });
                        }
                      }
                    });
                });
            } catch (error) {
              console.error(error);
            }
        }else{
          // 如果不需要提示直接调用收藏逻辑
          const data={"type":1,"bid":bid,"uid":this.user_id} //favor(1)=收藏词条   
          const res= this.favor(data); 
        }
      }else{
        // 执行取消收藏
        const data={
          "type":1,    //1=取消收藏  2=取消认领  
          "assets":1,  //1=词条 2=课程
          "uid":this.user_id,
          "bid":bid,
        }
        const res=await this.$commonFunctions.cancel_favorite(data)
        if(res==20000){
            // 重新查询词条信息
            this.fetchData_getWords();
            ElNotification({
                                message: "您已取消收藏",
                                title: "操作提示",
                                type: "info",
                                duration: 3000,  
                          }) 
        }else{
          ElNotification({
                            message: "取消失败",
                            title: "操作提示",
                            type: "info",
                            duration: 3000,  
                      }) 
        }
      }
     
    },

    async is_favorited(bid){
      console.log("is_favorited入参检查："+bid)
      
      const data={
            user_id:this.user_id,
            method:1, //1=收藏 2=认领 
            page:this.page,
            page_size:config.PAGE_SIZE,
            bids:[bid],
          }
      try{
        console.log("is_favorited/words_ownership的入参检查："+JSON.stringify(data));
        // 增加一个接口查词条的所属关系
        const response= await axios.post("/api/get_words_ownership/",data,{withCredentials:true})
        console.log("is_favorited的出参检查："+(response.data.code))
        if (response.data.code===20000)
          return(true)
        else
          return (false) 
      }             
      catch(error){
        console.log(error)
        return (false) 
      }
      
    },


    async favor(data){
       // 判断favorite按钮的状态
       const request={
        "type":data.type,     //1=收藏词条，
        "bid":data.bid,
        "uid":data.uid,
      }
       const res=await this.$commonFunctions.favorite(request)
      ElNotification({
          message: res.msg,
          title: "操作提示",
          type: "info",
          duration: 3000, 
      })
    },

    async do_share(bid){
      const rcode=await this.$commonFunctions.get_promotion_code(this.user_id)
      const pcode=rcode.promotion_code;
      const hyper_linker=config.share_domain_name+"H5promotion?"+"source=share"+"&bid="+bid+"&pcode="+pcode
      
      try {
        await new Promise(() => {
          ElMessageBox.alert(hyper_linker, '分享地址', {
            confirmButtonText: '复制地址',
            customStyle: 'overflow-wrap: break-word',
            callback: (action) => {
               if (action==='confirm'){
                  //更新分享数据
                  this.update_interactivedata([bid],"share_count","plus",0.0001)
               }else if(action==='cancel'){
                 console.log("提示对话框关闭")
               }
            }
          });
        });

        const res = this.copy2clipboard(hyper_linker);
        console.log("elMB.alert回调函数的返回值是：" + res);

        if (res === true) {
          ElMessage({
            type: 'success',
            message: '已复制到剪贴板',
          });
        } else {
          ElMessage({
            type: 'error',
            message: '复制失败，请尝试手动复制',
          });
        }
      } catch (error) {
        console.error(error);
      }
   
    },

    
    copy2clipboard(hyper_linker){
      try{
            navigator.clipboard.writeText(hyper_linker)
            console.log("copy2clipboard成功！")
            return true
          }catch(err){
          console.log("copy2clipboard失败！原因是："+err)
          // ElNotification({
          //                 message: "请检查浏览器配置是否允许进行复制",
          //                 title: "操作提示",
          //                 type: "warning",
          //                 duration: 3000,
          //             });
          return  false  }
    },

    async like(bid){
      this.show_animation=!this.show_animation
      let current_time=Date.now()
      console.log("本次执行时间："+current_time+" bid: "+bid)
      //设置定时器 10分钟内只允许一次
      if(current_time-this.last_update_likedata_time>=10*60*1000 || this.last_bid!=bid){
         await this.update_interactivedata([bid],"like_count","plus",0.0001)
        console.log("下次可执行时间："+Number(this.last_update_likedata_time)+10*60*1000);
      }else{
        console.log("未到下次执行时间")
        ElNotification({
                          message: "点赞太快的，你的爱我承受不住 :D",
                          title: "操作提示",
                          type: "warning",
                          duration: 3000,
                      });
      }
    },


   async update_interactivedata(bid,type,method,value){
    const data={
            "bid":bid,
            "type":type,
            "method":method,
            "val":value
          };
          console.log("update_interactivedata入参检查：bid="+bid+" type="+type+" method="+method+" val="+value);
      await axios.post("/api/update_interactivedata/",data,{withCredentials:true})
                        .then(response=>
                        {
                            try{
                                if(response.data['code']==20000){ 
                                  const interactive_data={
                                                "user_id":this.user_id,
                                                "method":decodeURIComponent(this.$route.params.param1)==""?this.$props.param1:decodeURIComponent(this.$route.params.param1),
                                                "bids":bid
                                              }
                                      // 查询对应词条的点赞数和收藏关系
                                      this.$commonFunctions.check_interactive_status(interactive_data).then(
                                        response=>{
                                          if(response.code==20000){
                                            console.log("udpate_interactivedata函数检查interactive_res出参检查："+JSON.stringify(response.data))
                                            if(response.data!==null||response.data!==""){
                                              this.interactiveData.likes=response.data[bid].like_count;
                                              this.interactiveData.shares=response.data[bid].share_count;
                                              console.log("udpate_interactivedata函数检查interactive_dict的赋值情况："+JSON.stringify(this.interactive_dict))
                                              //更新缓存数据
                                              // 获取当前cookie的值
                                                  const cookieValue = document.cookie.replace(new RegExp(`(?:(?:^|.*;\\s*)interactive_dict\\s*=\\s*([^;]*).*$)|^.*$`), "$1");

                                                  // 解析为JavaScript对象
                                                  const cookieObject = JSON.parse(cookieValue);

                                                  // 更新bid对应的值
                                                  const updatedValue = {
                                                    like_count: this.interactiveData.likes,
                                                    share_count:this.interactiveData.shares
                                                  };
                                                  cookieObject[bid] = updatedValue;

                                                  // 将更新后的对象转换回字符串形式
                                                  const updatedCookieValue = JSON.stringify(cookieObject);

                                                  // 更新cookie的值
                                                  document.cookie = `interactive_dict=${updatedCookieValue}; path=/`;
                                            }                                
                                              this.last_update_likedata_time= Date.now();
                                              this.last_bid=bid
                                              console.log("udpate_interactivedata函数更新最后执行时间"+this.last_update_likedata_time+" 本次执行的bid："+this.last_bid)
                                          }
                                        }
                                      ) 
                                }
                              }
                            catch(error){
                                console.log(error)
                            }
                      })
      },

   async get_properties(activeNames){
    console.log("当前展开的卡片business_id="+activeNames)
    try{
        const cookie_interactive_dict=JSON.parse(this.$commonFunctions.get_cookies("interactive_dict").replace(/'/g,"\""))
        if(activeNames in cookie_interactive_dict){  
            console.log("检查get_properties函数里like_count="+JSON.stringify( cookie_interactive_dict[activeNames]))
            this.interactiveData.likes=cookie_interactive_dict[activeNames].like_count;
            this.interactiveData.shares=cookie_interactive_dict[activeNames].share_count;
            //console.log("检查get_properties函数里获取的likes数： "+this.interactiveData.likes)
        }else{
        console.log("当前卡片 "+activeNames+" 记录不存在")
      }
      }catch(err){
        console.log(err)
      }
    },

    
    // 页面初始化
    user_profiles(){
      return new Promise((resolve,reject)=>{
         const login_token= this.$commonFunctions.get_cookies('login_token')
         this.$commonFunctions.get_user_profiles(login_token)
         .then((response)=>{
          this.user_id=response.user_id
          resolve(this.user_id)
         })
         .catch(error=>{
          reject(error);
         });  
      });
    },
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
span.contributerWords{
  vertical-align: super;
}

.el-avatar--circle{
  margin-right: 1dvw;
}

span.index{ 
  font-weight: 400;
  font-size: 13px;
  color:rgba(0,0,0,0.45); 
}
span.english {
  display: block;
  font-weight: 600;
  font-size: 13px;
  color:rgba(0,0,0,0.8);
  cursor: pointer;
}
span.chinese{
  display:block;
  font-weight: 400;
  font-size: 13px;
  color:rgba(0,0,0,0.65);
}
div.contributer{
  border-top:1px dashed rgba(51,51,51,0.15);
  text-align: right;
  padding-top: 3.5dvh;
  color: rgba(0,0,0,0.45);
}
::v-deep .el-collapse-item__content{
   padding-bottom: 1.5dvh;
   padding-left: 16px;
}
div.el-row.sentences{
  margin-bottom: 3dvh;
  text-align: left;
}
div.pronouns{
  width: 100%;
  text-align: left;
  color:rgba(0,0,0,0.45);
  font-size: 13px;
  font-weight: 400;
  margin-bottom: 3dvh;
  cursor: pointer;
}

img.playButton{
  padding:0px 10px;
  width:15px;
  height:15px;
}

img.avatar{
  padding:0px 10px;
  width:30px;
  height:30px;
  border-radius: 50%;
}

::v-deep .el-collapse-item__header{
  font-weight: 500 ;
  font-size: 14px;
  text-align: left;
  padding:1.5dvh 2dvw;
}

h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
.interactive_button>span{
  margin-right: 10px;
}

/*动画效果*/
.v-enter-from,
.v-leave-to {
  opacity: 0;
}
/* 离开和进入过程中的样式 */
.v-enter-active{
 transform: translateY(30px);  
  opacity: 0;  
  transition: transform 0.25s ease-out, opacity 0.25s ease-out;  }
.v-leave-active {
  /* 添加过渡动画 */
   transform: translateY(30px);  
  opacity: 1;  
  transition: transform 1s ease-out, opacity 1s ease-out;  
}
/* 进入之后和离开之前的样式 */
.v-leave-to,
.v-enter-to {
   transform: translateY(-30px);  
  opacity: 0;  
}
.box {  
  padding: 20px;  
  height: 45px;
  width: auto;
} 

.like_animation{
  position: absolute;
  left: 0;
  z-index: 9;
}

div.words_content{
 position: relative;
 z-index: 1; 
}
.audit_falut{
  border: 1px solid #7b7b7b;
  color:#7b7b7b;
}
.auditing{
  border: 1px solid #4473d4;
  color:#4473d4;
}
</style>